package com.shamar.blog.util;

import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * created by xiaowei 2020-05-11 23:22:13
 */
public class MapUtil {

    /**
     * map拷贝
     * @param paramsMap
     * @return
     */
    public static Map mapCopy(Map paramsMap) {
        Map resultMap = new HashMap();
        if (paramsMap == null) return resultMap;
        Iterator it = paramsMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            resultMap.put(key, paramsMap.get(key) != null ? paramsMap.get(key) : "");
        }

        return resultMap;
    }

    /**
     * 忽略元素拷贝
     * @param sourceMap
     * @param ignoreKeys
     * @return
     */
    public static Map<String, String> mapCopy(Map<String, String> sourceMap, String... ignoreKeys) {
        Map resultMap = new HashMap();
        if (sourceMap == null) return resultMap;

        if (ignoreKeys == null || ignoreKeys.length ==0) return mapCopy(sourceMap);

        Iterator it = sourceMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String key = (String) entry.getKey();
            if(isArryContains(ignoreKeys, key)) continue;
            resultMap.put(key, sourceMap.get(key) != null ? sourceMap.get(key) : "");
        }
        return resultMap;
    }


    /**
     * 判断数组元素是否存在
     * @param arr
     * @param ret
     * @return
     */
    private static boolean isArryContains(String[] arr, String ret) {
        for (String srt : arr) {
            if (srt.equals(ret)) return true;
        }
        return false;
    }


    public static void main(String[] args) {
        Map<String, String> map = Maps.newHashMap();
        map.put("buyer_name", "22");
        map.put("buyer_id_no", "1");
        map.put("busss", "dfd");
        System.out.println(map);
        System.out.println(MapUtil.mapCopy(map, "buyer_name", "buyer_id_no"));
        System.out.println(MapUtil.mapCopy(map));
    }

}
